package pers.cz.transform;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.LoaderClassPath;

import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @program: MyAgent
 * @description: CostTimeTransformer
 * @author: Cheng Zhi
 * @create: 2022-02-05 19:31
 **/
public class InterfaceTransformer implements ITransformer {

    public final String TEST_CLASS_NAME = "com.ailk.ims.httpjson.servlet.ImsActionDispatcher";
    //public final String TEST_CLASS_NAME = "com.cz.business.TestCaseBusiness";

    public final String METHOD_NAME = "invoke";
    //public final String METHOD_NAME = "queryAllTestCaseByPage";

    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        String finalClassName = className.replace("/", ".");
        if (finalClassName.equals(TEST_CLASS_NAME)) {
            // 动态修改代码
            try {
                ClassPool classPool = new ClassPool(true);
                classPool.insertClassPath(new LoaderClassPath(loader));
                // 获取目标类
                CtClass ctClass = classPool.get(TEST_CLASS_NAME);
                // 获取要监听的方法
                CtMethod beginMethod = ctClass.getDeclaredMethod(METHOD_NAME);
                //beginMethod.insertAfter("com.cz.agent.Collect.begin($args);");
                String beginSrc = "{pers.cz.mock.InterfaceMock.begin(busiCode,soMode);}";
                beginMethod.insertAt(200, beginSrc);
                String src =
                        "{" +
                                "pers.cz.mock.InterfaceMock.middle(data, json.toString(), busiCode);" +
                                "}";
                beginMethod.insertAt(297, src);
                //beginMethod.insertAt(68, src);
                // 加载到jvm
                return ctClass.toBytecode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    public void doInert(String... params) {

    }
}
